<template>
  <div class="container">
    <div class="left">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="类型">
          <el-select
            placeholder="选择类型"
            clearable
            style="width: 210px"
            @change="changeType"
            v-model="type"
          >
            <el-option label="视频" value="1" />
            <el-option label="图片" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-upload
        action="#"
        accept="video/*"
        :http-request="fnUploadRequest"
        :before-upload="handleSuccess"
        :on-change="uploadVideoChange"
        :on-error="handleError"
        :show-file-list="false"
        :file-list="videos"
        multiple
        v-if="role == 3"
      >
        <el-button type="primary">选择视频</el-button>
      </el-upload>
      <el-upload
        action="#"
        accept="image/*"
        :http-request="fnImgUploadRequest"
        :on-change="uploadImgChange"
        :before-upload="handleSuccess"
        :on-error="handleError"
        :show-file-list="false"
        :file-list="files"
        multiple
        v-if="role == 3"
      >
        <el-button type="primary">选择图片</el-button>
      </el-upload>
    </div>
    <div class="list">
      <div v-for="item in list" :key="item.id" class="videoBox">
        <div v-if="type == '1'" class="box">
          <video :src="item.url[0]" controls class="video" />
          <div class="code" @click="getQrcode(item.id)">二维码</div>
        </div>
        <div class="box" v-else>
          <img :src="item.url[0]" />
          <div class="code" @click="getQrcode(item.id)">二维码</div>
        </div>
      </div>
    </div>
    <div class="page">
      <el-pagination
        background
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-dialog v-model="showQrcode" width="400">
    <div class="qr">
      <img :src="QCode" />
    </div>
  </el-dialog>
</template>
<script setup>
import { ref, watch, onMounted } from "vue";
import { client } from "@/utils/oss";
import router from "@/router";
import qrcode from "qrcode";
import {
  fileList,
  fileUserList,
  imageUpload,
  videoUpload,
  qr_code,
} from "@/api/admin";
const list = ref([]);
const currentPage = ref(1);
const page_size = ref(10);
const type = ref("1");
const total = ref();
const userInfo = localStorage.getItem("userInfo");
const token = userInfo ? JSON.parse(userInfo).token : "";
const role = userInfo ? JSON.parse(userInfo).role : "";
const files = ref([]);
const videos = ref([]);
const isUploading = ref(false);
const QCode = ref();
const showQrcode = ref(false);
onMounted(() => {
  if (!token) {
    router.push("/");
  }
});
const changeType = (val) => {
  type.value = val;
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
};
const handleSizeChange = (val) => {
  page_size.value = val;
};
const getQrcode = async (id) => {
  const res = await qr_code({ file_id: id });
  if (res.code === 0) {
    qrcode.toDataURL(res.data.share_url, (err, url) => {
      if (err) {
        console.log(err);
      } else {
        QCode.value = url;
      }
    });
    showQrcode.value = true;
  }
};
const getfilelist = () => {
  const fn = role == 3 ? fileList : fileUserList;
  fn({
    page: currentPage.value,
    page_size: page_size.value,
    type: Number(type.value),
    token,
  }).then((res) => {
    list.value = res.data.list;
    total.value = res.data.total;
  });
};
watch(
  [currentPage, page_size, type],
  () => {
    getfilelist();
  },
  { immediate: true }
);
const fnImgUploadRequest = async () => {
  if (isUploading.value) return;
  isUploading.value = true;
  const ossClient = client();
  const fileList = files.value;
  const name = fileList[0].raw.name;
  const results = [];
  try {
    for (let i = 0; i < fileList.length; i++) {
      const data = fileList[i];
      const fileName = new Date().getTime() + "_" + data.raw.name;
      const result = await ossClient.put(fileName, data.raw);
      results.push(result.url);
    }
    const params = { name, urls: results, token };
    const res = await imageUpload(params);
    if (res.code === 0) {
      type.value = "2";
      if (currentPage.value === 1) {
        getfilelist();
      } else {
        currentPage.value = 1;
      }
    }
  } catch (e) {
    console.log("上传图片失败", e);
  } finally {
    isUploading.value = false;
    files.value = [];
  }
};
const fnUploadRequest = async () => {
  if (isUploading.value) return;
  isUploading.value = true;
  const ossClient = client();
  const fileList = videos.value;
  const results = [];
  try {
    for (let i = 0; i < fileList.length; i++) {
      const data = fileList[i];
      const name = data.raw.name;
      const fileName = new Date().getTime() + "_" + data.raw.name;
      const result = await ossClient.put(fileName, data.raw);
      results.push({ name, url: [result.url] });
    }
    const params = { files: results, token };
    const res = await videoUpload(params);
    if (res.code === 0) {
      type.value = "1";
      if (currentPage.value === 1) {
        getfilelist();
      } else {
        currentPage.value = 1;
      }
    }
  } catch (e) {
    console.log("上传视频失败", e);
  } finally {
    isUploading.value = false;
    videos.value = [];
  }
};
const handleSuccess = () => {
  console.log("Upload success:");
};
const uploadImgChange = (file, fileList) => {
  files.value = fileList;
};
const uploadVideoChange = (file, fileList) => {
  videos.value = fileList;
};
const handleError = () => {
  console.error("Upload error:");
};
</script>
<style scoped>
.container {
  padding: 50px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
.left {
  display: flex;
  gap: 20px;
  height: 40px;
}
.list {
  flex: 1;
  display: flex;
  gap: 20px;
  .videoBox {
    display: flex;
    gap: 20px;
    margin-top: 20px;
    .box {
      width: 180px;
      height: 180px;
      position: relative;
      background: #eae5e5;
      img {
        width: 100%;
        height: 100%;
      }
      .video {
        width: 100%;
        height: 100%;
      }
      .code {
        width: 70px;
        height: 30px;
        position: absolute;
        top: 8px;
        right: 5px;
        text-align: center;
        line-height: 30px;
        background: #fff;
        cursor: pointer;
        font-size: 14px;
      }
    }
  }
}
.page {
  margin-top: 10px;
  height: 100px;
  display: flex;
  justify-content: end;
}
.qr {
  width: 100%;
  height: 360px;
  margin: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    width: 250px;
    height: 250px;
  }
}
</style>
